<template>
  <div class="task-download-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchExportVisible" inline :model="searchExportForm" ref="searchExportForm"
               @keyup.enter.native="searchExportHandle">
        <el-form-item prop="taskType" label="类型">
          <el-select v-model="searchExportForm.taskType" clearable size="mini" placeholder="请选择任务类型"
                     class="search-form-select">
            <el-option
              v-for="taskType in taskTypeOptions"
              :key="taskType.value"
              :label="taskType.label"
              :value="taskType.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="downloadMode" label="模式">
          <el-select v-model="searchExportForm.downloadMode" clearable size="mini" placeholder="请选择任务模式"
                     class="search-form-select">
            <el-option label="异步下载" value="0"></el-option>
            <el-option label="同步下载" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="fileType" label="文件">
          <el-select v-model="searchExportForm.fileType" clearable size="mini" placeholder="请选择文件类型"
                     class="search-form-select">
            <el-option label="xlsx" value="0"></el-option>
            <el-option label="csv" value="1"></el-option>
            <el-option label="xls" value="2"></el-option>
            <el-option label="txt" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="searchExportForm.status" clearable size="mini" placeholder="请选择导出状态"
                     class="search-form-select">
            <el-option label="正在导出" value="0"></el-option>
            <el-option label="导出成功" value="1"></el-option>
            <el-option label="导出失败" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="deleteFlag">
          <el-select v-model="searchExportForm.deleteFlag" clearable size="mini" placeholder="请选择删除状态"
                     class="search-form-select">
            <el-option label="正常" value="0"></el-option>
            <el-option label="删除" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="searchExportForm.createTime1"
            type="date"
            size="mini"
            placeholder="请选择开始时间"
            :picker-options="createTime1PickerOptions"
            @change="datePickerInputHandle($event, true)"
            class="search-form-date-picker">
          </el-date-picker>
          至
          <el-date-picker
            v-model="searchExportForm.createTime2"
            type="date"
            size="mini"
            placeholder="请选择结束时间"
            :picker-options="createTime2PickerOptions"
            @input="datePickerInputHandle($event, false)"
            class="search-form-date-picker">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" size="mini" type="primary" plain icon="el-icon-search"
                     @click="searchExportHandle">查询</el-button>
          <el-button :disabled="dataLoad" size="mini" plain icon="el-icon-refresh-right"
                     @click="resetSearchExportFormHandle">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="t-d-tool">
      <el-button :disabled="buttonDisabled" type="danger" size="mini"
                 plain icon="el-icon-delete" @click="deleteExportTaskHandle">删除</el-button>
      <!-- 表格工具组件 -->
      <right-tool-bar :search-visible="searchExportVisible"
                      @toggle-search="searchExportVisible = !searchExportVisible" @refresh-table="getExportList(false)" />
    </div>

    <!-- 导出任务表格 -->
    <el-table
      v-loading="dataLoad"
      :data="exportList"
      ref="exportTable"
    >
      <el-table-column type="selection" align="center" width="50"></el-table-column>
      <el-table-column prop="taskTypeName" align="center" label="任务名称"></el-table-column>
      <el-table-column prop="downloadMode" align="center" label="导出模式">
        <template v-slot="scope">
          {{ scope.row.downloadMode === 0 ? '异步下载' : '同步下载' }}
        </template>
      </el-table-column>
      <el-table-column prop="fileType" align="center" label="文件类型">
        <template v-slot="scope">
          {{ fileTypeFormat(scope.row.fileType) }}
        </template>
      </el-table-column>
      <el-table-column prop="fields" align="center" label="导出字段" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="dataType" align="center" label="数据类型">
        <template v-slot="scope">
          {{ scope.row.dataType === 0 ? '当前页' : scope.row.dataType === 1 ? '全部' : '自选' }}
        </template>
      </el-table-column>
      <el-table-column prop="dataRow" align="center" label="总数"></el-table-column>
      <el-table-column prop="showParams" align="center" label="请求参数" width="100" show-overflow-tooltip>
        <template v-slot="scope">
          <span @click="lookParamsHandle(scope.row.showParams)" :class="{ 't-d-params': scope.row.showParams }">
            {{ scope.row.showParams }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="导出状态" width="80">
        <template v-slot="scope">
          <el-tag :class="'t-d-status' + scope.row.status">
            {{ scope.row.status === 0 ? '正在导出' : scope.row.status === 1 ? '导出成功' : '导出失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="deleteFlag" align="center" label="状态" width="80">
        <template v-slot="scope">
          <el-tag :type="scope.row.deleteFlag === 0 ? 'success' : 'danger'">
            {{ scope.row.deleteFlag === 0 ? '正常' : '删除' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" align="center" label="开始时间"></el-table-column>
      <el-table-column prop="endTime" align="center" label="结束时间"></el-table-column>
      <el-table-column prop="createTime" align="center" label="创建时间"></el-table-column>
      <el-table-column prop="remark" align="center" label="备注" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" width="120" label="操作">
        <template v-slot="scope">
          <el-button v-if="downloadDisabled(scope.row)" :disabled="dataLoad" type="text" @click="downloadFileHandle(scope.row.taskId)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页插件 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="searchExportForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchExportForm.limit"
      :total="exportSize"
      :disabled="dataLoad"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 导出任务请求参数显示弹出框 -->
    <params-view :dialog-visible="paramsDialogVisible" @close-params-view-dialog="paramsDialogVisible = false"
                 ref="paramsView" />

  </div>
</template>

<script>
  import ParamsView from "@/components/task/params-view";
  import RightToolBar from '@/components/common/right-toolbar';

  export default {
    layout: 'admin',
    name: "admin-task-download",
    components: { ParamsView, RightToolBar },
    data() {
      return {
        // 导出任务列表
        exportList: [],
        // 符合条件的导出任务数量
        exportSize: 0,
        // 任务类型下拉框可选项数组
        taskTypeOptions: [],
        // 数据是否加载[true-加载 false-不加载]
        dataLoad: false,
        // 导出任务检索是否显示[true-显示 false-不显示]
        searchExportVisible: true,
        // 博客检索表单对象
        searchExportForm: {
          // 任务类型
          taskType: '',
          // 任务模式[0-异步下载 1-同步下载]
          downloadMode: '',
          // 文件类型[0-xlsx 1-csv 2-xls 3-txt]
          fileType: '',
          // 任务状态[0-正在导出 1-导出成功 2-导出失败]
          status: '',
          // 删除状态[0-正常 1-删除]
          deleteFlag: '',
          // 创建时间（开始）
          createTime1: '',
          // 创建时间（结束）
          createTime2: '',
          // 页码
          page: 1,
          // 每页大小
          limit: 10,
          // 排序字段
          field: 'createTime',
          // 排序方式
          order: 'ascending'
        },
        // 创建时间（开始）组件适配类
        createTime1PickerOptions: {},
        // 创建时间（结束）组件适配类
        createTime2PickerOptions: {},
        // 导出任务请求参数显示弹出框是否显示[true-显示 false-不显示]
        paramsDialogVisible: false,
      }
    },
    computed: {
      /**
       * 按钮是否禁用
       * 满足以下条件之一即禁用
       *  1、数据加载
       *  2、菜单列表为空
       *  3、选中行为空
       * @returns {boolean} true-禁用 false-可点击
       */
      buttonDisabled() {
        return this.dataLoad || this.exportSize === 0 || this.$refs.exportTable.selection.length === 0
      },
    },
    created() {
      if (process.client) {

        this.getExportList(false)
      }
    },
    methods: {
      /**
       * 获取用户导出任务列表方法
       * @param {boolean} bool 是否重置页码[true-重置 false-不重置]
       */
      getExportList(bool) {
        // 表格数据加载
        this.dataLoad = true

        let searchExportForm = this.searchExportForm
        if (bool) {
          searchExportForm.page = 1
        }

        this.$axios.$post('/common/export-task/list', searchExportForm)
          .then(({ data }) => {
            this.exportList = data.data
            this.exportSize = data.totalNum
          })
          .catch(() => {})
          .finally(() => {
            // 表格加载结束
            this.dataLoad = false
          })
      },
      /**
       * 用户导出任务检索事件
       */
      searchExportHandle() {
        let searchExportForm = this.searchExportForm
        if (searchExportForm.createTime1 !== '') {
          let date = searchExportForm.createTime1
          if (date instanceof Date) {
            searchExportForm.createTime1 = date.getTime()
          }
        }
        if (searchExportForm.createTime2 !== '') {
          let date = searchExportForm.createTime2
          if (date instanceof Date) {
            date.setMinutes(59)
            date.setSeconds(59)
            date.setMilliseconds(999)
            searchExportForm.createTime2 = date.getTime()
          }
        }

        this.getExportList(true)
      },
      /**
       * 删除导出任务事件
       */
      deleteExportTaskHandle() {
        let array = this.$refs.exportTable.selection
        // 获取可以被删除的导出任务id数组
        let taskIds = array.filter(exportTask => exportTask.deleteFlag === 0).map(exportTask => exportTask.taskId)
        if (taskIds.length === 0) {
          this.notify('info', '温馨提示', '选中数据行中可以删除的数据行为空，请确认。')
          return
        }
        this.$confirm('您确定要删除选中的导出任务吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          this.$axios.$delete('/common/export-task/delete', { data: taskIds })
            .then(() => {
              this.notify('success', '操作成功', '删除导出任务成功')

              this.getExportList(false)
            })
            .catch(() => {})
        }).catch(() => {
          this.notify('info', '温馨提示', '已取消‘删除’操作')
        });
      },
      /**
       * 查看导出任务请求参数事件
       * @param {string} params 请求参数对象（文字描述）
       */
      lookParamsHandle(params) {
        if (!params) {
          this.notify('info', '提示', '没有请求参数');
          return;
        }
        if (params === '{}') {
          this.notify('info', '提示', '请求参数为空');
          return;
        }
        this.paramsDialogVisible = true;

        this.$nextTick(() => {
          this.$refs.paramsView.initParams('导出任务参数列表', params);
        });
      },
      /**
       * 下载导出任务关联的文件事件
       * @param {string} taskId 导出任务主键值
       */
      downloadFileHandle(taskId) {
        // 开始文件下载
        this.dataLoad = true
        this.$axios.$get('/common/export-task/download', { params: { taskId }, responseType: 'blob' })
          .then(data => {
            if (data instanceof Blob) {
              /*
                1、请求失败
               */
              let reader = new FileReader()
              // 成功回调
              reader.onload = res => {
                // 得到字符串
                let { result } = res.target
                // 解析成json对象
                let data = JSON.parse(result)
                // console.log('data', data)
                this.notify('warning', '温馨提示', data.msg)
              }
              // 按照utf-8编码解析
              reader.readAsText(data, 'utf-8')
              return
            }
            /*
              2、请求成功
             */
            // 创建一个a标签的dom元素
            let downloadElement = document.createElement('a');
            // 创建文件下载的链接
            let href = window.URL.createObjectURL(data.data);
            // 设置下载连接
            downloadElement.href = href;
            // 下载的文件名
            downloadElement.download = decodeURI(data.fileName);
            // 页面添加dom元素
            document.body.appendChild(downloadElement);
            // 点击下载
            downloadElement.click();
            //下载完成移除dom元素
            document.body.removeChild(downloadElement);
            //释放掉文件下载的链接对象
            window.URL.revokeObjectURL(href);

            this.notify('success', '操作成功', '导出文件下载成功')
          })
          .catch(() => {})
          .finally(() => {
            // 文件下载结束
            this.dataLoad = false
          })
      },
      /**
       * 导出任务表格显示大小切换事件
       */
      sizeChangeHandle(size) {
        let searchExportForm = this.searchExportForm
        searchExportForm.page = 1
        searchExportForm.limit = size

        this.getExportList(false)
      },
      /**
       * 导出任务表格页码切换事件
       */
      currentChangeHandle(index) {
        let searchExportForm = this.searchExportForm
        if (searchExportForm.page === index) {
          return
        }
        searchExportForm.page = index
        this.getExportList(false)
      },
      /**
       * 重置用户导出任务检索表单事件
       */
      resetSearchExportFormHandle() {
        let searchExportForm = this.searchExportForm
        if (searchExportForm.taskType === '' && searchExportForm.downloadMode === '' && searchExportForm.fileType === '' &&
          searchExportForm.status === '' && searchExportForm.deleteFlag === '' && searchExportForm.createTime1 === '' &&
          searchExportForm.createTime2 === '' && searchExportForm.page === 1 && searchExportForm.limit === 10) {
          this.notify('info', '温馨提示', '导出任务检索条件不满足重置条件，重置失败。')
          return
        }

        searchExportForm.taskType = ''
        searchExportForm.downloadMode = ''
        searchExportForm.fileType = ''
        searchExportForm.status = ''
        searchExportForm.deleteFlag = ''
        searchExportForm.createTime1 = ''
        searchExportForm.createTime2 = ''
        searchExportForm.page = 1
        searchExportForm.limit = 10

        this.getExportList(false)
      },
      /**
       * 文件类型值转为成中文显示[0-xlsx 1-csv 2-xls 3-txt]
       * @param {number} fileType 文件类型
       */
      fileTypeFormat(fileType) {
        switch (fileType) {
          case 0:
            return 'xlsx'
          case 1:
            return 'csv'
          case 2:
            return 'xls'
          case 3:
            return 'txt'
          default:
            return ''
        }
      },
      /**
       * 创建时间开始/结束日期组件选择事件
       * @param {Date} date    选中的日期
       * @param {boolean} bool 操作的组件[true-创建时间（开始） false-创建时间（结束）]
       */
      datePickerInputHandle(date, bool) {
        let searchExportForm = this.searchExportForm
        if (!date) {
          /*
            清空选中的值，进入此块代码
           */
          if (bool) {
            // 创建时间（开始）
            searchExportForm.createTime1 = ''
            this.createTime2PickerOptions = {
              disabledDate: () => {
                return false
              }
            }
          } else {
            // 创建时间（结束）
            searchExportForm.createTime2 = ''
            this.createTime1PickerOptions = {
              disabledDate: () => {
                return false
              }
            }
          }
          return
        }
        if (date instanceof Date) {
          let timeNumber = date.getTime()
          if (bool) {
            // 创建时间（开始）
            searchExportForm.createTime1 = timeNumber

            this.createTime2PickerOptions = {
              disabledDate: time => {
                // 创建时间（开始）可选项不能小于创建时间（结束）
                return time < timeNumber
              }
            }
          } else {
            // 创建时间（结束）
            searchExportForm.createTime2 = timeNumber

            this.createTime1PickerOptions  = {
              disabledDate: time => {
                // 创建时间（开始）可选项不能大于创建时间（结束）
                return time > timeNumber
              }
            }
          }
        }
      },
      /**
       * 导出任务文件下载按钮是否禁用
       * 满足以下条件之一即禁用
       * 1、任务模式不是异步下载
       * 2、任务状态不是成功状态
       * 3、任务已经删除
       * @param {Object} exportTask 导出任务对象
       */
      downloadDisabled(exportTask) {
        return exportTask.downloadMode === 0 && exportTask.status === 1 && exportTask.deleteFlag === 0
      },
    }
  }
</script>

<!--
  css字符对应
  d -> download
  t -> task
-->
<style scoped>
  .task-download-page .search-form-select {
    width: 140px;
  }
  .task-download-page .search-form-date-picker {
    width: 150px;
  }
  .task-download-page .t-d-tool {
    margin-bottom: 10px;
  }
  .task-download-page .paging {
    text-align: right;
    margin: 10px;
  }
  .task-download-page .t-d-status0 {
    color: #43C49D;
  }
  .task-download-page .t-d-status1 {
    color: #13ce66;
  }
  .task-download-page .t-d-status2 {
    color: #f14b4b;
  }
  .task-download-page .t-d-params {
    cursor: pointer;
  }
  .task-download-page .t-d-params:hover {
    color: #17B3A3;
  }
</style>
